#include "stdafx.h"
#include "hereBaseSocket.h"

hereBaseSocket::hereBaseSocket(void)
{
	WSADATA wsd = {0};

	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
		throw( "WSAStartup failed!" );
	m_bConnect = FALSE;
}

hereBaseSocket::~hereBaseSocket(void)
{
	if ( m_bConnect )
		disconnect();
	WSACleanup();
}

int hereBaseSocket::connect(char *s_addr_dst, USHORT u_port)
{
	SOCKADDR_IN servAddr = {0};
	int nServAddlen = 0;
	int retVal = 0;

	m_lSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( INVALID_SOCKET == m_lSocket )
	{
		throw( "Init socket failed!" );
		return -1;
	}

	servAddr.sin_family =AF_INET;
	servAddr.sin_addr.s_addr = inet_addr(s_addr_dst);
	servAddr.sin_port = htons((short)u_port);
	nServAddlen = sizeof(servAddr);

	retVal = ::connect(m_lSocket,(LPSOCKADDR)&servAddr, sizeof(servAddr));
	if( SOCKET_ERROR == retVal )
	{
		closesocket(m_lSocket);
		return -1;
	}

	m_bConnect = TRUE;

	return 0;
}

void hereBaseSocket::disconnect()
{
	if ( m_bConnect )
	{
		closesocket(m_lSocket);
		m_bConnect = FALSE;
	}
}

int hereBaseSocket::send_req(char *buf, int len)
{
	int ret = 0;

	CONNECT_CHECK();
	ret = send(m_lSocket, buf, len, 0);
	if ( SOCKET_ERROR == ret)
		disconnect();

	return ret;
}

int hereBaseSocket::recv_resp(char *buf, int len)
{
	int ret = 0;

	CONNECT_CHECK();
	ret = recv(m_lSocket, buf, len, 0);
	if ( SOCKET_ERROR == ret)
		disconnect();

	return ret;
}